package org.tio.sitexxx.web.server.controller.gl;



import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.i18n.Res;
import com.jfinal.plugin.activerecord.*;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.*;
import  com.alibaba.fastjson.JSONObject;
import org.tio.sitexxx.service.service.qj.*;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.web.server.controller.minip.kf_order;
import org.tio.utils.resp.Resp;

import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.List;

@RequestPath("/m_admin")
public class AdminController {
    private static Logger log = LoggerFactory.getLogger(AdminController.class);
    /**
     * 获取充值套餐
     * @return
     */
    @RequestPath("/getCharge")
    public Resp getCharge(){
        List<Charge>list=ChargeService.me.getAll();
        if(list==null)return Resp.fail();
        return Resp.ok(list);
    }

    /**
     * 添加充值套餐
     * @param request request
     * @return  Resp
     * @throws IOException
     */
    @RequestPath("/addCharge")
    public Resp addCharge(HttpRequest request) throws IOException {
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        Charge charge= JSON.parseObject(JSON.toJSONString(map),Charge.class);
        System.out.println("charge:"+JSON.toJSONString(charge));
        Date date=new Date();
        charge.setCreatedAt(date);
        charge.setUpdatedAt(date);
        try{
            boolean flag=ChargeService.me.save(charge);
            if(flag){
                return Resp.ok();
            }
        }catch (Exception e){
            log.error(e.toString(),e);
        }
       return Resp.fail();
    }

    /**
     *
     * 删除充值套餐
     * @param request request
     * @return Resp
     */
    @RequestPath("/delCharge")
    public Resp delCharge(HttpRequest request){
        Integer id =Integer.valueOf(request.getParam("id"));
        System.out.println("id:"+id);
        ChargeService.me.delCharge(id);
        return Resp.ok();
    }

    /**
     * 允许注册顾问
     * @param request request
     * @return Resp
     */
    @RequestPath("/consultantAudit")
    public Resp consultantAudit(HttpRequest request ){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        System.out.println("map:"+JSON.toJSONString(map));
        Map<String,Object> result = new HashMap();
        try{
            Integer id = Integer.valueOf(map.get("id").toString());
            String isPass = (String)map.get("isPass");
            if(id==null||isPass==null)return Resp.fail();
            result.put("id",id);
            Consultant consultant= ConsultantService.me.getConsultant(result);
            if(isPass.equals("1")){
                consultant.setAudit(true);
                if(consultant.getInterestId()==null||consultant.getInterestId()==0){
                    Date date=new Date();
                    Record interest=new Record().set("id",consultant.getId()).set("commission_rate", 0.5f).set("grade",3)
                            .set("createdAt",date).set("updatedAt",date);
                    Db.use(Const.Db.TIO_SITE_MAIN).save("interest","id",interest);
                    consultant.setInterestId(interest.get("id"));
                }
            }else {
                consultant.setAudit(false);
            }
            ConsultantService.me.update(consultant);
            result.put("ok",1);
        }catch (NullPointerException e){
            log.error(e.toString(),e);
            return Resp.fail("参数错误");
        }catch (Exception se){
            log.error(se.toString(),se);
            return Resp.fail("error:"+ se.getMessage());
        }
        return Resp.ok(result);
    }

    /**
     * 呆审核列表consultant
     * @return  Resp
     */
    @RequestPath("/consultant")
    public Resp consultant(){
        List<Consultant> list=ConsultantService.me.consultantAudit();
        if(list==null||list.isEmpty())return Resp.ok("暂无待审核申请");
        return Resp.ok(list);
    }

    /**
     * 删除顾问
     * @param request request
     * @return
     */
    @RequestPath("/consultant/delete")
    public Resp consultantDel(HttpRequest request ){
        try{
            Map<String,Object>map= JSON.parseObject(request.getBodyString());
            Integer id =Integer.valueOf(map.get("id").toString());
            System.out.println("id:"+id);
            ConsultantService.me.deleteById(id);
            return Resp.ok("删除成功");
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return Resp.fail();
    }

    /**
     * 用户形象测试过后顾问分析 并给出结论
     * @param request
     * @return
     * @throws IOException
     */
    @RequestPath("/member/modify")
    public Resp memberModify(HttpRequest request ) throws IOException {
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            Integer id=Integer.valueOf(map.get("id").toString());
            String color=map.get("color")==null?"暂无":map.get("color").toString();
            String shape=map.get("shape").toString();
            String style=map.get("style").toString();
            System.out.println("id:"+id+"color:"+color+"shape:"+shape+"style:"+style);
            Map<String,Object>temp=new HashMap<>(2);
            temp.put("id",id);
            Member member= MemberService.me.getMember(temp);
            if(member==null)return Resp.fail("用户不存在");
            member.setTested("0");//1为用户提交了形象测试，0为顾问提交过了结论 null为用户没有提交形象测试
            Imagetesting imagetesting = ImagetestingService.me.fingById(id);
            if(imagetesting==null)return Resp.fail("用户没有参加形象测试");
            imagetesting.setColour(color);
            imagetesting.setShape(shape);
            imagetesting.setStyle(style);
            imagetesting.setUpdatedAt(new Date());
            System.out.println("imagetest:"+JSON.toJSONString(imagetesting));
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    boolean result=member.update();
                    boolean result2=imagetesting.update();
                    if(result&&result2){
                        return true;
                    }
                    return false;
                }
            });
         return Resp.ok(imagetesting);
        }catch (NullPointerException e){
            log.error(e.toString(),e);
            return Resp.fail("参数错误");
        }catch (NumberFormatException e){
            log.error(e.toString(),e);
            return Resp.fail("部分参数不能为空");
        }catch (Exception se){
            log.error(se.toString(),se);
            return Resp.fail();
        }
    }

    /**
     * 管理员设置
     * 只有管理员才有审核顾问，设置客服的权限
     * @param request
     * @return
     */
    @RequestPath("/auth_manager")
    public Resp auth_manager(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            Integer consultantId=Integer.valueOf(map.get("consultantId").toString());
            String sql="update consultant set is_manager=1 where id=?";
            int result=Db.use(Const.Db.TIO_SITE_MAIN).update(sql,consultantId);
            boolean is_manager=(result==1);
            if(is_manager)return Resp.ok("设置成功");
            return Resp.fail("设置失败");
        }catch (RuntimeException e){
            if(e instanceof NullPointerException){
                return Resp.fail("参数错误");
            }
            throw e;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Resp.fail();
        }
    }
    /**
     * 管理员设置
     * 只有管理员才有审核顾问，设置客服的权限
     * @param request
     * @return
     */
    @RequestPath("/auth_manager/cancel")
    public Resp auth_managerCancel(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            Integer consultantId=Integer.valueOf(map.get("consultantId").toString());
            String sql="update consultant set is_manager=0 where id=?";
            int result=Db.use(Const.Db.TIO_SITE_MAIN).update(sql,consultantId);
            boolean is_manager=(result==1);
            if(is_manager)return Resp.ok("设置成功");
            return Resp.fail("设置失败");
        }catch (RuntimeException e){
            if(e instanceof NullPointerException){
                return Resp.fail("参数错误");
            }
            throw e;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Resp.fail();
        }
    }

    /**
     * 获取不是管理员的顾问
     * @return
     */
    @RequestPath("/consultantList")
    public Resp consultantList(){
        String sql="select * from consultant where is_manager=0";
        List<Consultant>consultants=Consultant.dao.find(sql);
        if(consultants.isEmpty()){
            return Resp.ok("暂无不是管理员的顾问");
        }
        return  Resp.ok(consultants);
    }

    /**
     * 顾问修改头像
     * @param request
     * @return
     */
    @RequestPath("/consultant/modify_avatar")
    public Resp modify_avatar(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            String openid=String.valueOf(map.get("openid"));
            String avatar=String.valueOf(map.get("avatar"));
            if("null".equals(avatar))return Resp.fail("头像不能为空");
            boolean result1=Db.tx(()->{
                //简单SQL直接写在这了。。
                //在lambda表达式的语句块中，定义变量不能与外围变量重名，lambda表达式可以接受外围常量为参数，这就不足为奇了
                String consultantsql="update consultant set avata=? where openid=?";
                String usersql="update user set avatar=? where loginname=?";
                int userresult=Db.use(Const.Db.TIO_SITE_MAIN).update(usersql,avatar,openid);
                int result=Db.use(Const.Db.TIO_SITE_MAIN).update(consultantsql,avatar,openid);
                boolean flag1=(userresult==1);
                boolean flag2=(result==1);
                if(flag1&&flag2){
                    return true;
                }
                return false;
            });
            if(result1)return Resp.ok("修改成功");
            return Resp.fail("修改失败");
        }catch (RuntimeException e){
            if(e instanceof NullPointerException){
                return Resp.fail("参数错误");
            }
            throw e;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Resp.fail();
        }
    }
    /**
     * 用户修改头像
     * @param request
     * @return
     */
    @RequestPath("/modify_avatar")
    public Resp modify_avatar_member(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            String openid=String.valueOf(map.get("openid"));
            String avatar=String.valueOf(map.get("avatar"));
            if("null".equals(avatar))return Resp.fail("头像不能为空");
            //简单SQL直接写在这了。。
            boolean result=Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    String membersql="update member set avatar=? where openid=?";
                    String sql="update  user set avatar=? where loginname=?";
                    int userresult=Db.use(Const.Db.TIO_SITE_MAIN).update(membersql,avatar,openid);
                    int result=Db.use(Const.Db.TIO_SITE_MAIN).update(sql,avatar,openid);
                    if((userresult==1)&&(result==1))return true;
                    return false;
                }
            });
            if(result)return Resp.ok("修改成功");
            return Resp.fail("修改失败");
        }catch (RuntimeException e){
            if(e instanceof NullPointerException){
                return Resp.fail("参数错误");
            }
            throw e;
        }catch (Exception e){
            log.error(e.toString(),e);
            return Resp.fail();
        }
    }

    /**
     * 获取所有未评价的用户衣橱
     * @param pageNum  从一开始
     * @param pageSize
     * @return
     */
    @RequestPath("/get_wardrobe_not_assess")
    public Page<Wardrobe> get_wardrobe_not_assess(Integer pageNum,Integer pageSize){
        if(null==pageNum||null==pageSize)return null;
        String sql="wardrobe.getWardrobes_not_assess";
        SqlPara sqlPara=Db.use(Const.Db.TIO_SITE_MAIN).getSqlPara(sql);
        Page<Wardrobe> pages=Wardrobe.dao.paginate(pageNum,pageSize,sqlPara);
        return pages;
    }

    /**
     * 获取当前客服
     * @return
     */
    @RequestPath("/get/kf")
    public Resp getKf(){
        String sql="select * from consultant where is_kf=1";
        List<Consultant> consultants=Consultant.dao.find(sql);
        if(consultants.isEmpty()){
            return Resp.ok("暂无数据");

        }
        return Resp.ok(consultants);
    }
    /**
     * 获取不是客服的顾问
     * @return
     */
    @RequestPath("/get/consultant")
    public Resp getConsultant(){
        String sql="select * from consultant where id in(select id from consultant_service_staff where openid is not null ) and audit =1 and is_kf =0 order by consultant.seq";
        List<Consultant> consultants=Consultant.dao.find(sql);
        if(consultants.isEmpty()){
            return Resp.ok("暂无数据");

        }
        return Resp.ok(consultants);
    }


    /**
     * 设置客服
     * @param request
     * @return
     */
    @RequestPath("/set/kf")
    public Resp setKf(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            String openid=String.valueOf(map.get("openid"));
            /*String cancel="select * from consultant where is_kf=1";
            Consultant consultant=Consultant.dao.findFirst(cancel);*/
            String sql="update consultant set is_kf=1 where openid=?";
            /*if(consultant!=null){
                boolean result=Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {
                        consultant.setIsKf(false);
                        boolean cancelresult=consultant.update();
                        int userresult=Db.use(Const.Db.TIO_SITE_MAIN).update(sql,openid);
                        if(cancelresult&&(userresult==1))
                        return true;
                        return false;
                    }
                });
                if(result)return Resp.ok("设置成功，先前客服已被当前客服覆盖");
                return Resp.fail("设置失败");

            }*/
            int userresult=Db.use(Const.Db.TIO_SITE_MAIN).update(sql,openid);
            boolean success=(userresult==1);
            if(!success)return Resp.fail("设置失败");
            return Resp.ok("设置成功");
        }catch (Exception e){
            log.error(e.toString(),e);
            return  Resp.fail();
        }
    }

    /**
     * 取消设置客服
     * @param request
     * @return
     */
    @RequestPath("/cancel/kf")
    public Resp cancel_kf(HttpRequest request){

        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            String openid=String.valueOf(map.get("openid"));
            if(StrUtil.isBlank(openid))return Resp.fail("参数不能为空");
            String sql="select * from consultant where openid=?";
            Consultant consultant=Consultant.dao.findFirst(sql,openid);
            if(ObjectUtil.isNull(consultant))return Resp.fail("顾问不存在");
            if(!consultant.getIsKf())return Resp.fail("该顾问不是客服无法取消");
            consultant.setIsKf(false);
            boolean scuuess=consultant.update();
            if(scuuess)return Resp.ok("设置成功");
            return Resp.fail("设置失败");
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return Resp.fail();
    }

    /**
     * 获取全部未评价的个人私人衣橱
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestPath("/wardrobe/list")
    public Resp getWardrobeList(Integer pageNum,Integer pageSize){
        if(null==pageNum||pageSize==null||pageNum<0||pageSize<0)return Resp.fail();
        ArrayList<Map<String,Object>>resultList=new ArrayList<>();
        String sql="SELECT * FROM qj_main.wardrobe w  where w.suitable is null and paid =1 and memberId=? order by w.updatedAt desc";

        String getMemberSql="SELECT * FROM qj_main.wardrobe w  where w.suitable is null and paid =1 group by memberId order by w.updatedAt desc limit ?,?";

        String sqlcount="SELECT count(distinct memberId) FROM qj_main.wardrobe w  where w.suitable is null and paid =1";

        int totalcount=Db.use(Const.Db.TIO_SITE_MAIN).queryInt(sqlcount);
        //获取用户id
        List<Wardrobe>wardrobeList=Wardrobe.dao.find(getMemberSql,pageNum*pageSize,pageSize);
        System.out.println("wardrobeList:"+JSON.toJSONString(wardrobeList));
        if(!wardrobeList.isEmpty()){//deal with
            wardrobeList.forEach(wardrobe -> {
                int memberId=wardrobe.getMemberId();
                Map<String,Object> member= WardrobeService.me.getMemberAndWardrobr(memberId);
                System.out.println("member:"+member);
                List<Wardrobe>wardrobes=Wardrobe.dao.find(sql,memberId);
                if(null!=member){
                    Map<String,Object>map=JSON.parseObject(JSON.toJSONString(member),Map.class);
                    map.put("wardrobe",wardrobes);
                    map.put("count",totalcount);
                    resultList.add(map);
                }
                if(null==member){
                    Map<String,Object> temp=new HashMap<>(2);
                    temp.put("id",memberId);
                    Member member1=MemberService.me.getMember(temp);
                    if(null!=member1){
                        Map<String,Object>map=JSON.parseObject(JSON.toJSONString(member1),Map.class);
                        map.put("wardrobe",wardrobes);
                        map.put("count",totalcount);
                        resultList.add(map);
                    }
                }
            });
        }
        return Resp.ok(resultList);
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestPath("/kf/order/list")
    public Resp getOrderList(Integer pageNum,Integer pageSize){
        if(null==pageNum||pageSize==null||pageNum<0||pageSize<0)return Resp.fail();

        return Resp.fail();
    }

    /**
     *
     * @param request
     * @return
     */
    @RequestPath("/consultant/modify/name")
    public Resp modify_name(HttpRequest request){
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            String openid=String.valueOf(map.get("openid"));
            String name=String.valueOf(map.get("name"));
            Consultant consultant=ConsultantService.me.getConsultantByOpenId(openid);
            if(null==consultant)return Resp.fail("顾问不存在");
            consultant.setName(name);
            boolean result=consultant.update();
            if(result)
                return Resp.ok("修改成功");
            return Resp.fail("修改失败");
        }catch (NullPointerException e){}catch (Exception e){
            log.error(e.toString(),e);
        }
        return Resp.fail();
    }


}
